<template>
  <div>
    <el-card>
      <el-descriptions title="就诊信息" direction="vertical" :column="4" border>
        <el-descriptions-item label="患者名称" :span="2">{{ clinicForm.patientName }}</el-descriptions-item>
        <el-descriptions-item label="患者来源" :span="2">{{ dict.type.patient_source[(clinicForm.source)*1].label }}</el-descriptions-item>
        <el-descriptions-item label="病种" :span="1">{{ dict.type.disease[(clinicForm.disease)*1].label }}</el-descriptions-item>
        <el-descriptions-item label="科室" :span="1">{{ dict.type.department[(clinicForm.department)*1].label }}</el-descriptions-item>
        <el-descriptions-item label="病区" :span="1">{{  dict.type.ward[(clinicForm.ward)*1].label}}</el-descriptions-item>
        <el-descriptions-item label="病床" :span="1">{{ clinicForm.bedNum }}</el-descriptions-item>
        <el-descriptions-item label="诊断" :span="4">{{ clinicForm.preDiagnose }}</el-descriptions-item>
        <el-descriptions-item label="病情摘要" :span="4">{{ clinicForm.illnessSummary }}</el-descriptions-item>
        <el-descriptions-item label="既往史" :span="4">{{ clinicForm.preHistory }}</el-descriptions-item>
        <el-descriptions-item label="家族史" :span="4">{{ clinicForm.familyHistory }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-card>
        <div slot="header">
          <span>医生信息</span>
        </div>
        <div>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="主治医生" prop="masterName">-->
<!--              <el-input v-model="masterName" placeholder="请输入主治医师姓名" readonly/>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="评估医生" prop="doctorId">
              <!--              <el-input v-model="form.doctorId" placeholder="请输入病区" />-->
              <el-select v-model="form.doctorId" placeholder="请输入评估医生姓名">
                <el-option
                  v-for="item in userOptions"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="8" :span="8" style="display:flex;justify-content: right">
            <el-button type="success" @click="topinggu">本人评定</el-button>
          </el-col>
        </div>
      </el-card>
      <el-card>
        <div slot="header">
          <span>评定信息</span>
        </div>
        <div>
          <el-col :span="8">
            <el-form-item label="评定表名称" prop="assessId">
              <el-input v-model="assessName" style="width: 70%" placeholder="请在下方选择评定表" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="5">-->
<!--            <el-checkbox v-model="form.charge">收费</el-checkbox>-->
<!--          </el-col>-->
        </div>
        <div style="text-align: right">
          <el-button type="primary" @click="submitForm">评估医师评定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-card>

      <!--      <span>{{ this.form }}</span>-->
    </el-form>

    <div style="display: flex;justify-content: center;">
      <el-card style="width: 100%;">
        <div slot="header">
          <span>评定表列表</span>
        </div>
        <div>
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="150px"
                   style="text-align: right">
            <el-form-item label="按表类别查询" prop="pdType" >
              <el-select v-model="queryParams.pdType" placeholder="请选择评定表类别" clearable>
                <el-option
                  v-for="cat in categoryList "
                  :key="cat.id"
                  :label="cat.name"
                  :value="cat.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="输入表名查询" prop="assessName">
              <el-input
                v-model="queryParams.assessName"
                placeholder="请输入评定表名称"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item style="margin:auto 40px">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table style="margin-top: 20px" v-loading="loading" :data="assessList" @selection-change="handleSelectionChange">
          <el-table-column label="评定表编号" align="center" prop="assessId" width="150"/>
          <el-table-column label="评定表名称" align="center" prop="assessName"/>
          <el-table-column label="评定表配置" align="center" prop="assessConfig" width="600"/>
          <el-table-column label="类别" align="center" prop="pdType"></el-table-column>
          <el-table-column label="备注" align="center" prop="remark" width="60"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleAssign(scope.row)"
              >分配
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>
    </div>
  </div>
</template>

<script>

import {delAssess, getAssess, listAssess} from "@/api/gaoxin/assess";
import {addTask, delTask, getTask, listTaskalive} from "@/api/gaoxin/taskdata";
import {getAuthAssess, getUser, getUserAll} from "@/api/system/user";
import {getUserProfile} from "@/api/system/user";
import {getClinic} from "@/api/gaoxin/clinic";
import {listCategory} from "@/api/system/category";

export default {
  name: "Task",
  dicts: ['department','disease','ward','marital_status','sys_user_sex','patient_source'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      assessName: "",
      // 表单参数
      clinicId: '',
      clinicForm: {},
      categoryList:[],
      form: {
        clinicId: '',
        masterId: "",
        doctorId: "",
        assessId: "",
        status: "1",
        charge:true
      },
      //患者数据
      patientOptions: [],
      userOptions: [],
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // assess数据
      assesses: [],
      // assess表格数据
      assessList: [],
      tempList: [],
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assessName: null,
        pdType: null,
      },

      // 表单校验
      rules: {
        masterId: [{
          required: true,
          message: "主治医生不能为空",
          trigger: ['blur']
        }
        ],
        doctorId: [{
          required: true,
          message: "评估医生不能为空",
          trigger: ['blur']
        }],
        assessId: [
          {
            required: true,
            message: "评定表选择不能为空",
            trigger: ['blur']
          }
        ],
      },
      //分配任务医生姓名
      masterName: "",
    };
  },
  created() {

    const path = this.$route.path;
    const clinicId = Number(path.split('/').slice(-1));
    this.clinicId = clinicId;
    this.form.clinicId = clinicId;
    console.log(this.$route)

    getUserProfile().then(res => {
      this.form.masterId = res.data.userId;
      this.masterName = res.data.nickName;
    })
    this.getInfo();
    this.getList();
    this.getListCategory();
  },
  watch: {
    "form.doctorId": {
      handler(newVal, oldVal) {
        this.assesses = null;
        let tempList = [];
        this.assessList = null;
        getAuthAssess(newVal).then(response => {
          this.assesses = response.assesses;
          for (let i = 0; i < this.assesses.length; i++) {
            if (this.assesses[i].flag) {
              tempList.push(this.assesses[i]);
            }
          }
          this.assessList = tempList;
          console.log(tempList)
        });
      }
    }
  },
  methods: {
    topinggu() {
      this.$modal.confirm('是否确认评估医生为本人，且现在就开始评估').then(() => {
        getUserProfile().then(res => {
          console.log(this.form)
          this.form.doctorId = res.data.userId;
          this.$refs["form"].validate(valid => {
            if (valid) {
              this.form.charge=this.form.charge?1:0;
              addTask(this.form).then(() => {
                console.log(this.form)
                listTaskalive(this.form).then(res => {
                  var tasklist = res.rows;
                  var task = tasklist[tasklist.length - 1]
                  this.$router.push({
                    name: 'dataAdd', params: {
                      taskdata: task,
                      assid: this.form.assessId
                    }
                  });
                })
              });
            }
          });
        })
      })
    },

    getInfo() {
      getUserAll().then(response => {
        this.userOptions = response.users;
      });
      let clinicId = this.clinicId;
      getClinic(clinicId).then(response => {
        this.clinicForm = response.data;
        console.log(this.clinicForm)
      })
    },
    handleAssign(row) {
      this.form.assessId = row.assessId || this.ids
      this.assessName = row.assessName;
      console.log(this.assessName);
    },

    selectPatientInfo() {
      console.log(this.patientOptions);
      let item = this.patientOptions.find(item => item.patientId === this.form.patientId)
      this.form.ward = item.ward;
      this.form.department = item.department;
    },

    /** 查询assess列表 */
    getList() {
      this.loading = true;
      listAssess(this.queryParams).then(response => {
        this.assessList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getListCategory() {
      this.loading = true;
      listCategory().then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAuthAssess(userId) {
      this.loading = true;
      console.log(this.assessList)
      this.assessList = null;
      console.log(this.assessList)
      getAuthAssess(userId).then(response => {
        this.assesses = response.assesses;
        for (let i = 0; i < this.assesses.length; i++) {
          if (this.assesses[i].flag) {
            this.assessList.push(this.assesses[i]);
          }
        }
        // this.assesses.forEach((row) => {
        //   if (row.flag) {
        //     this.assessList.push(row);
        //   }
        // });
        console.log(this.assessList)
      });
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.$tab.closePage()
      this.$router.go(-1)
    },
    // 表单重置
    reset() {
      this.form = {
        assessId: null,
        assessName: null,
        assessConfig: null,
        remark: null,
        charge:null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.assessId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加assess";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const assessId = row.assessId || this.ids
      getAssess(assessId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改assess";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.charge=this.form.charge?1:0;
          addTask(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
            this.$tab.closeOpenPage({path: "/taskdata"})
          });
        }
      });

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const assessIds = row.assessId || this.ids;
      this.$modal.confirm('是否确认删除assess编号为"' + assessIds + '"的数据项？').then(function () {
        return delAssess(assessIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/assess/export', {
        ...this.queryParams
      }, `assess_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>

.el-card {
  margin-bottom: 20px;
}
.el-checkbox{
  margin-top: 5px;
  zoom: 120%;
}
</style>
